<script setup>
import { useI18n } from 'vue-i18n'
import mitt from '@/mitt'
import uploadIcon from '../iconSvg/uploadIcon.vue'

const { t } = useI18n()
const props = defineProps({
  fileType: {
    type: String,
    default: ''
  },
  useButton: {
    type: Boolean,
    default: true
  },
  fileChange: {
    type: Function,
    default: () => {
      return () => {}
    }
  }
})

const uploadRef = ref(null)

const uploadHandle = () => {
  uploadRef.value?.submit()
}

const customRequest = ({
  file,
  data,
  headers,
  withCredentials,
  action,
  onFinish,
  onError,
  onProgress
}) => {
  const formData = new FormData()
  if (data) {
    Object.keys(data).forEach((key) => {
      formData.append(key, data[key])
    })
  }
  formData.append(file.name, file.file)
  // lyla
  //   .post(action, {
  //     withCredentials,
  //     headers,
  //     body: formData,
  //     onUploadProgress: ({ percent }) => {
  //       onProgress({ percent: Math.ceil(percent) })
  //     }
  //   })
  //   .then(({ json }) => {
  //     message.success(JSON.stringify(json))
  //     onFinish()
  //   })
  //   .catch((error) => {
  //     message.success(error.message)
  //     onError()
  //   })
}

const beforeUpload = (data) => {
  if (props.fileType == '') {
    return true
  }
  if (data.file.file?.type !== props.fileType) {
    mitt.emit('messageTip', {
      type: 'error',
      msg: 'system.fileTypeError',
      useTranslate: true
    })
    return false
  }
  return true
}
const fileListLength = ref(0)
const handleChange = (options) => {
  fileListLength.value = options.fileList.length
  props.fileChange && props.fileChange(options.fileList)
}

defineExpose({
  uploadHandle
})
</script>

<template>
  <n-upload
    ref="uploadRef"
    :custom-request="customRequest"
    :default-upload="false"
    @before-upload="beforeUpload"
    @change="handleChange"
  >
    <n-upload-dragger>
      <div style="margin-bottom: 12px">
        <n-icon size="48" :depth="3">
          <uploadIcon />
        </n-icon>
      </div>
      <n-text style="font-size: 16px"> {{ t('system.uploadTip') }} </n-text>
      <!-- <n-p depth="3" style="margin: 8px 0 0 0">
        请不要上传敏感数据，比如你的银行卡号和密码，信用卡号有效期和安全码
      </n-p> -->
    </n-upload-dragger>
  </n-upload>
  <div class="flex justify-end my-2" v-if="useButton">
    <n-button :disabled="!fileListLength" type="primary" @click="uploadHandle">{{
      t('system.upload')
    }}</n-button>
  </div>
</template>

<style scoped></style>
